<template>
  <div>
    <el-dialog title="模板管理" :visible.sync="temanagementDialogData.dialogVisible" width="60%">
      <div style="margin-bottom:20px">
        <el-button @click="newBtn" type="primary">新增</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="templateName" label="模板名称" align="center">
        </el-table-column>
        <el-table-column prop="tagType" label="审批类型" align="center"></el-table-column>
        <el-table-column prop="per" label="人员选择" align="center">
          <template slot-scope="scope">
            <span v-for="item in JSON.parse(scope.row.userjson)">{{item.ryName}}、</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
            >编辑</el-button
            >
            <el-button type="text" size="small" @click="delBtn(scope.row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
                      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background
                      layout="total, sizes, prev, pager, next, jumper"
                      style="margin-top: 10px;text-align: right;">
      </el-pagination>
      <el-dialog title="模板管理" :visible.sync="dialogVisible" width="40%" append-to-body>
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="模板名称" style="width: 100%" prop="templateName">
            <el-input v-model="form.templateName"></el-input>
          </el-form-item>

          <el-form-item label="审批类型" style="width: 100%" prop="tagType">
            <el-select
              v-model="form.tagType"
              placeholder="请选择审批类型"
              style="width: 100%"
            >
              <el-option v-for="(item,index) in tagTypeList" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员选择" prop="per">
            <label slot="label">
               <el-button type="primary" @click="chosseBtn">人员选择</el-button>
            </label>
            <span v-for="item in perList">{{item.ryName}}、</span>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('form')"
          >确 定</el-button
          >
          <el-button @click="backBtn">取 消</el-button>
        </span>
      </el-dialog>
    </el-dialog>
    <rckhselectUser
      ref="rckhselectUser"
      :multiple="true"
      :roleCode="roleCode"
      :userIds="userContractIds"
      @getUserList="getUserContract"
    ></rckhselectUser>
  </div>
</template>
<script>
import {
    getContractTypeDict,
    isExsitTemplateNamejy,
    saveTemplate,
    getemPage,
    deleteBatch,
    getDeptId
} from "@/api/dailyExamine/targetExamine/indicatorFormulation";

import rckhselectUser from "@/components/form/compound/rckhselectUser";
  export default {
    props: {
      temanagementDialogData: {},
    },
    components:{
        rckhselectUser
    },
    data() {
      const validatePer = (rule, value, callback) => {
        if (this.perList.length < 1) {
          callback(new Error("请选择人员"));
        } else {
          callback();
        }
      };
      return {
        tableData: [],
        form: {},
        perList: [],
        tagTypeList:[
          {name:"会签",value:"1"},
          {name:"顺序签",value:"2"},
        ],
        rules: {
          templateName: [
            { required: true, message: "请输入模板名称", trigger: "blur" },
          ],
          tagType:[{ required: true, message: "请选择审批类型", trigger: "change" }],
          per: [{ required: true, message: "请选择人员",validator: validatePer, }],
        },
        userContractIds:[],
        dialogVisible: false,
        roleCode :"HTRW_ADMIN",
        deptId:"",
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        loading:false,
        id:"",
        menuType:""
      };
    },
    watch: {
      temanagementDialogData: {
        handler(newVal, oldVal) {
          console.log(newVal)
          if (newVal.dialogVisible) {
            this.menuType = newVal.type;
            this.fngetemPage();
          }
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      fngetemPage(){
        this.loading = true;
        var param = {
          current: this.pageIndex,
          size: this.pageSize,
          menuType:this.menuType,
          tagName:"指标考核"
        }
        getemPage(param).then((res)=>{
          this.tableData = res.data.data.records;
          this.totalPage = res.data.data.total;
          this.loading = false;
        })
      },
      // 新增弹窗
      newBtn() {
        this.dialogVisible = true;
        this.form = {};
        this.perList = [];
        this.fngetDeptId();
        this.id = "";
      },
      //人员选择
      chosseBtn(){
        var perdata = {
          deptId:this.deptId,
          roleCode:"HTRW_ADMIN",
          perList:this.perList,
        };
       //console.log()
        this.$nextTick(()=>{
          this.$refs.rckhselectUser.zbndInit(perdata);
        })

      },
      // 选择人员返回的人员列表
      getUserContract(data){
        this.perList = data
      },
      // 获取部门deptId
      fngetDeptId(){
        getDeptId().then((res)=>{
         //console.log(res.data)
          this.deptId = res.data.data
        })
      },
      submitForm(formName) {
        var arr = []
        this.perList.forEach(ele=>{
          var obj = {}
          obj.ryName = ele.ryName;
          obj.userId = ele.userId;
          arr.push(obj)
        })
        var parmas = {
          userjson:JSON.stringify(arr),
          templateName:this.form.templateName,
          tagType:this.form.tagType,
          menuType:this.menuType,
          tagName:"指标考核"
        }
        var parmas2={
          userjson:JSON.stringify(arr),
          templateName:this.form.templateName,
          tagType:this.form.tagType,
          menuType:this.menuType,
          id:this.id,
          tagName:"指标考核"
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.id == ''){
              isExsitTemplateNamejy({
              templateName:this.form.templateName,
              menuType:this.menuType,
              tagName:"指标考核"
              }).then((res)=>{
                if(res.data.data){
                  this.$message.closeAll();
                  this.$message.warning("考核类别"+this.form.templateName+"已存在");
                }else{
                  this.save(parmas)
                }
              })
            }else{
              this.save(parmas2)
            }
          } else {
           //console.log("error submit!!");
            return false;
          }
        });
      },
      save(parmas){
        saveTemplate(parmas).then((response)=>{
          if(response.data.code == 0){
            this.$message.closeAll();
            this.$message.success(response.data.data);
            this.backBtn();
          }
        })


      },
      backBtn(){
        this.dialogVisible = false;
        this.form = {};
        this.perList = [];
        this.id = "";
        this.fngetemPage();
      },
      handleClick(row) {
        this.fngetDeptId()
        this.id = row.id
        this.form = row;
        this.perList =JSON.parse(row.userjson)
        this.dialogVisible = true;

      },
      delBtn(row) {
       //console.log(row)
        var params = {
          ids:row.id
        }
        deleteBatch(params).then((res)=>{
          if(res.data.code == 0){
            this.$message.closeAll();
            this.$message.success(res.data.data);
            this.fngetemPage()
          }
        })

      },
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.fngetemPage()
      },
        // 当前页
      currentChangeHandle(val) {
          this.pageIndex = val
          this.fngetemPage()
      },
    },
  };
</script>
